import _ from "lodash";
import { EnumErrorCode } from "../../../../../common/enum/EnumErrorCode";
import { EnumRoomType } from "../../../../../common/enum/EnumRoomType";
import { CS_Bet } from "../../../../../common/protocols/Proto_Bet";
import { Tools } from "../../../../../framework/utils/Tools";
import { RewardManager } from "../../controller/RewardManager";
import { UserEntity } from "../../controller/UserEntity";
import { GameRoomEntity } from "./GameRoomEntity";

export class GameRoomFastSingle extends GameRoomEntity {


    public type: EnumRoomType = EnumRoomType.FAST_SINGLE;

    constructor() {
        super();
    }

    public start(): void {

    }

    public canVote(): boolean {

        return false;
    }
    async vote(user: UserEntity, cs: CS_Bet): Promise<EnumErrorCode> {

        return new Promise(async (resolve, reject) => {
            if (!this.canVote()) {
                resolve(EnumErrorCode.CantVoteBet);
                return;
            }

            if (this.data.prizeId != cs.info.prizeID) {
                resolve(EnumErrorCode.CantVoteBet);
                return;
            }

            if (_.find(this.data.orders, { uid: cs.info.uid })) {
                resolve(EnumErrorCode.CantVoteBet);
                return;
            }

            _.each(cs.info.bets, bet => {
                this.data.prizePool += bet.coin;
            });

            const ret: EnumErrorCode = await this.saveOrder(user, cs.info);
            resolve(ret);

        });
        
    }
    public onUpdate(servertime: number): void {
          
    }

    /**
     * 开奖计算
     *
     * @memberof GameRoomFastSingle
     */
    public prizeDraw(): void {

        const rewardCodes: { [key: number]: number } = {};

        const result: number[] = [];
        for (let index = 0; index < this.config.codeNum; index++) {
            const code: number = Tools.getRandomNumber(this.config.rate);

            result.push(code);
            if (!rewardCodes[code]) {
                rewardCodes[code] = 0;
            }
            rewardCodes[code] += 1;
        }

        let totalRate: number = 0;

        let codeSum: number = 0;


        _.each(this.config.rate, data => {
            totalRate += data.rate;
            codeSum += 1;
        })

        /**先计算当前code的赔率 */
        _.each(this.data.orders, order => {
            let totalWin: number = 0;
            _.each(order.bets, bet => {
                if (rewardCodes[bet.key]) {
                    totalWin += rewardCodes[bet.key] * codeSum * bet.coin;
                }
            });

            order.win = totalWin;
            this.data.prizePool -= totalWin;
            order.result = result;
            //**有奖励管理器去派发奖励 */
            RewardManager.inst.addBetRewardOrder(order);
        })

        

    }

}